package com.atguigu.tingshu.album.api;

import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.UploadFileUtil;
import com.qcloud.vod.common.StringUtil;
import io.minio.*;
import io.minio.errors.*;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Tag(name = "上传管理接口")
@RestController
@RequestMapping("api/album")
public class FileUploadApiController {

    @Autowired
    private MinioConstantProperties minioConstantProperties;

    // 接受文件上传
    @PostMapping("fileUpload")
    public Result<String> fileUpload(@RequestParam("file") MultipartFile file){
        try {
            // 1.初始化minIO客户端，minIOClient:地址 用户名 密码
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioConstantProperties.getEndpointUrl())
                    .credentials(minioConstantProperties.getAccessKey(), minioConstantProperties.getSecretKey())
                    .build();

            // 2.判断对应的桶是否存在，不存在则创建
            if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build())){
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
            }

            // 3.把文件对象上传到对应的桶
            String fileName = UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(file.getOriginalFilename());
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(minioConstantProperties.getBucketName())
                    .object(fileName).stream(file.getInputStream(),file.getSize(),-1)
                    .contentType(file.getContentType())
                    .build());

            // 4.返回图片的访问地址: minio服务地址/bucket名/文件名
            return Result.ok(minioConstantProperties.getEndpointUrl()+"/" + minioConstantProperties.getBucketName() + "/" + fileName);
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }
}
